﻿using IdentityModel;
using IdentityServer4;
using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using RuoVea.ExConfig;
using RuoVea.ExCrypt;
using RuoVea.ExDto;
using RuoVea.ExUtil;
using RuoVea.Identity;
using RuoVea.Identity.Server;
using RuoVea.Identity.Utils;
using RuoVea.Server.Models;
using System.Diagnostics;
using System.Security.Claims;

namespace RuoVea.Server.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }
        [HttpGet("auth/login")]
        public IActionResult login(string returnUrl)
        {
            returnUrl = HttpContext?.Request?.QueryString.Value?.Replace("?returnurl=", "");

            returnUrl = returnUrl.IsNullOrWhiteSpace() ? Appsettings.GetSection("UserUI:RedirectUris").Value.Replace("/callback", "") : returnUrl;
            if (User.IsAuthenticated())
                return Redirect(returnUrl);
            return View(new { ReturnUrl=returnUrl });
        }
        
        [HttpPost("auth/login")]
        public async Task<bool> LoginAsync(string returnUrl,bool rememberLogin=false) {

            if (User.IsAuthenticated())
                 login(returnUrl);
            //returnUrl = HttpContext?.Request?.QueryString.Value?.Replace("?returnurl=", "");

            //returnUrl = returnUrl.IsNullOrWhiteSpace() ? Appsettings.GetSection("UserUI:RedirectUris").Value.Replace("/callback", "") : returnUrl;
            AuthenticationProperties props = new AuthenticationProperties();
            if (rememberLogin)
            {
                props = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1))
                };
            };

            var identityServerUser = new IdentityServerUser("10001")
            {
                DisplayName = "Account"
            };

            var claims = new List<Claim> {
                    new Claim(JwtClaimTypes.PreferredUserName,"admin"),
                    new Claim(ClaimConst.CLAINM_ACCOUNT, "admin"), 
                };

            identityServerUser.AdditionalClaims = claims;
            await HttpContext.SignInAsync(identityServerUser, props);
            string val = Guid.NewGuid().ToString();
            Response.Cookies.Append("token", val);
            return true;
        }
        
    }
}